package com.windliven.spoc.modules.init.config.shiro;

import com.windliven.spoc.modules.init.common.BizEnum;
import com.windliven.spoc.modules.init.exception.BizException;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

/**
 * @Author: bysun
 * @Date: 2019/5/26 10:03
 */
public class JwtAuthFilter extends BasicHttpAuthenticationFilter {

    private final String TOKEN = "token";

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        if (((HttpServletRequest) request).getHeader(TOKEN) != null) {
            try {
                executeLogin(request, response);
                return true;
            } catch (Exception e) {
                throw new BizException(BizEnum.ERROR);
            }
        }
        return true;
    }

    @Override
    protected boolean isLoginAttempt(ServletRequest request, ServletResponse response) {
        return super.isLoginAttempt(request, response);
    }

    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String token = httpServletRequest.getHeader(TOKEN);
        JwtToken jwtToken = new JwtToken(token);
        // 提交给realm进行登入，如果错误他会抛出异常并被捕获
        getSubject(request, response).login(jwtToken);
        // 如果没有抛出异常则代表登入成功，返回true
        return true;
    }
}
